package com.jsbb.util.digest;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * Aes加密
 *
 * @author w
 * @date 2021-03-05
 */
public class AesUtils {

    public static String encrypt(String data, String key) {
        String result = null;
        try {
            byte[] bytes = build(Cipher.ENCRYPT_MODE, data.getBytes(), key.getBytes());
            result = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String decrypt(String data, String key) {
        String result = null;
        try {
            byte[] src = Base64.getDecoder().decode(data);
            byte[] bytes = build(Cipher.DECRYPT_MODE, src, key.getBytes());
            result = new String(bytes, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static byte[] build(int mode, byte[] data, byte[] key) throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128, new SecureRandom(key));
        SecretKey secretKey = keyGen.generateKey();
        byte[] encoded = secretKey.getEncoded();
        SecretKeySpec keySpec = new SecretKeySpec(encoded, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode, keySpec);
        return cipher.doFinal(data);
    }
}
